﻿using DocumentFormat.OpenXml.Wordprocessing;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OpenXmlTools.OpenXML.Word
{
    /// <summary>
    /// Word表格内容对齐方式设置帮助类
    /// </summary>
    public static class WordTableAlignmentHelper
    {
        /// <summary>
        /// 设置表格内容对齐方式（水平垂直居中为默认）
        /// </summary>
        /// <param name="table">要设置对齐的表格</param>
        /// <param name="horizontalAlign">水平对齐方式（默认居中）</param>
        /// <param name="verticalAlign">垂直对齐方式（默认居中）</param>
        /// <param name="applyTo">应用范围（默认整个表格）</param>
        /// <param name="rowIndex">行索引（当applyTo为Row或Cell时有效）</param>
        /// <param name="cellIndex">单元格索引（当applyTo为Cell时有效）</param>
        public static void SetTableAlignment(
            Table table,
            HorizontalAlignment horizontalAlign = HorizontalAlignment.Center,
            VerticalAlignment verticalAlign = VerticalAlignment.Center,
            TableApplyTarget applyTo = TableApplyTarget.EntireTable,
            int rowIndex = 0,
            int cellIndex = 0)
        {
            // 获取目标单元格
            var targetCells = GetTargetCells(table, applyTo, rowIndex, cellIndex);

            foreach (var cell in targetCells)
            {
                // 设置水平对齐
                SetHorizontalAlignment(cell, horizontalAlign);

                // 设置垂直对齐
                SetVerticalAlignment(cell, verticalAlign);
            }
        }

        /// <summary>
        /// 设置表格内容默认居中（水平垂直居中）
        /// </summary>
        /// <param name="table">要设置居中的表格</param>
        /// <param name="applyTo">应用范围（默认整个表格）</param>
        /// <param name="rowIndex">行索引（当applyTo为Row或Cell时有效）</param>
        /// <param name="cellIndex">单元格索引（当applyTo为Cell时有效）</param>
        public static void SetTableCenter(Table table, TableApplyTarget applyTo = TableApplyTarget.EntireTable, int rowIndex = 0, int cellIndex = 0)
        {
            SetTableAlignment(table, HorizontalAlignment.Center, VerticalAlignment.Center, applyTo, rowIndex, cellIndex);
        }

        #region 私有辅助方法

        /// <summary>
        /// 获取目标单元格集合
        /// </summary>
        /// <param name="table">要设置居中的表格</param>
        /// <param name="applyTo">应用范围（默认整个表格）</param>
        /// <param name="rowIndex">行索引（当applyTo为Row或Cell时有效）</param>
        /// <param name="cellIndex">单元格索引（当applyTo为Cell时有效）</param>
        /// <returns>目标单元格集合</returns>
        private static IEnumerable<TableCell> GetTargetCells(Table table, TableApplyTarget applyTo, int rowIndex, int cellIndex)
        {
            switch (applyTo)
            {
                case TableApplyTarget.EntireTable:
                    return table.Descendants<TableCell>();

                case TableApplyTarget.Row:
                    var rows = table.Elements<TableRow>().ToList();
                    if (rowIndex >= 0 && rowIndex < rows.Count)
                    {
                        return rows[rowIndex].Elements<TableCell>();
                    }
                    break;

                case TableApplyTarget.Cell:
                    var rowList = table.Elements<TableRow>().ToList();
                    if (rowIndex >= 0 && rowIndex < rowList.Count)
                    {
                        var cells = rowList[rowIndex].Elements<TableCell>().ToList();
                        if (cellIndex >= 0 && cellIndex < cells.Count)
                        {
                            return new[] { cells[cellIndex] };
                        }
                    }
                    break;
            }

            return Enumerable.Empty<TableCell>();
        }

        /// <summary>
        /// 设置单元格垂直对齐
        /// </summary>
        /// <param name="cell">需要设置的单元格</param>
        /// <param name="verticalAlign">垂直对齐方式</param>
        private static void SetVerticalAlignment(TableCell cell, VerticalAlignment verticalAlign)
        {
            // 获取或创建单元格属性
            var cellProperties = GetOrCreateTableCellProperties(cell);

            // 移除现有垂直对齐属性
            var existingAlignment = cellProperties.GetFirstChild<TableCellVerticalAlignment>();
            existingAlignment?.Remove();

            // 添加新的垂直对齐设置
            TableVerticalAlignmentValues alignmentValue = verticalAlign switch
            {
                VerticalAlignment.Top => TableVerticalAlignmentValues.Top,
                VerticalAlignment.Bottom => TableVerticalAlignmentValues.Bottom,
                _ => TableVerticalAlignmentValues.Center // 默认居中
            };

            cellProperties.Append(new TableCellVerticalAlignment { Val = alignmentValue });
        }

        /// <summary>
        /// 设置单元格水平对齐
        /// </summary>
        /// <param name="cell">需要设置的单元格</param>
        /// <param name="horizontalAlign">水平对齐方式</param>
        private static void SetHorizontalAlignment(TableCell cell, HorizontalAlignment horizontalAlign)
        {
            foreach (var paragraph in cell.Elements<Paragraph>())
            {
                // 获取或创建段落属性
                var paragraphProperties = paragraph.GetFirstChild<ParagraphProperties>();
                if (paragraphProperties == null)
                {
                    paragraphProperties = new ParagraphProperties();
                    paragraph.PrependChild(paragraphProperties);
                }

                // 移除现有水平对齐属性
                var existingJustification = paragraphProperties.GetFirstChild<Justification>();
                existingJustification?.Remove();

                // 添加新的水平对齐设置
                JustificationValues justificationValue = horizontalAlign switch
                {
                    HorizontalAlignment.Left => JustificationValues.Left,
                    HorizontalAlignment.Right => JustificationValues.Right,
                    HorizontalAlignment.Justify => JustificationValues.Both,
                    _ => JustificationValues.Center // 默认居中
                };

                paragraphProperties.Append(new Justification { Val = justificationValue });
            }
        }

        /// <summary>
        /// 获取或创建单元格属性
        /// </summary>
        /// <param name="cell">单元格</param>
        /// <returns>单元格属性</returns>
        private static TableCellProperties GetOrCreateTableCellProperties(TableCell cell)
        {
            var cellProperties = cell.GetFirstChild<TableCellProperties>();
            if (cellProperties == null)
            {
                cellProperties = new TableCellProperties();
                cell.PrependChild(cellProperties);
            }
            return cellProperties;
        }

        #endregion
    }
}
